import { defineStore } from "pinia";
import pinia from "@/store";
import { LoginRequest,  refreshUserInfo, userLogin } from "@/api/user";


export const useUserStoreHook = defineStore("userInfo", {
  state: () : IUserState => ({
    username: "",
    accessToken: "",
    roles: [],
    permissions:[]
  }),
  getters: {},
  actions: {
    // Store user login information
    async storeUserLogin(data: LoginRequest) {
      try {
        const res = await userLogin(data);
        this.accessToken = res.accessToken;
        return res;
      } catch (error) {
        console.log(error);
        this.accessToken = '';
      }
    },

    async storeGetUserInfo() {
      try {
        const res = await refreshUserInfo({accessToken: this.accessToken,})
        this.username = res.username;
        this.roles = res.roles;
        this.permissions = res.permissions;
        return res
      } catch (error) {
        this.accessToken = '';
      }
    },

    async storeLogout(){
      this.username = '';
      this.accessToken = '';
      this.roles = [];
      this.permissions = []
      localStorage.removeItem("userInfo")
    }

  },

  persist:true
});

export function useUserStore() {
  return useUserStoreHook(pinia);
}